const express = require("express");
const router = express.Router();
const { Message } = require("../../models");
const { NotFound } = require("http-errors");
const { success, failure } = require("../../utils/responses");
const { Op } = require("sequelize");
const jwt = require("jsonwebtoken");

/**
 * 查询消息列表
 * GET /admin/messages
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      where: {},
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
    };
    if (query.status) {
      condition.where.status = query.status;
    }
    if (query.senderId) {
      condition.where.senderId = query.senderId;
    }
    if (query.receiverId) {
      condition.where.receiverId = query.receiverId;
    }
    if (query.type) {
      query.type = query.type.split(",");
      console.log("query.type", query.type);
      if (query.type.length > 1) {
        condition.where.type = {
          [Op.in]: query.type,
        };
      } else {
        condition.where.type = {
          [Op.in]: query.type[0],
        };
      }

      // condition.where.type = {
      //   [Op.in]: `%${query.type.split(',')}%`
      //   //[Op.in]: ['1', '2', '3', '4', '5']
      // }
    }

    if (query.level) {
      condition.where.level = query.level;
    }
    if (query.startDate && query.endDate) {
      condition.where.timestamp = {
        [Op.between]: [query.startDate, query.endDate],
      };
    }
    if (query.isWebSocket) {
      condition.where.isWebSocket = query.isWebSocket;
    }
    const { count, rows } = await Message.findAndCountAll(condition);
    success(req, res, "查询消息列表成功。", {
      list: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(req, res, error);
  }
});
// 一键已读
router.put("/readAll", async function (req, res) {
  try {
    const { token } = req.headers;

    if (!token) {
      throw new Error("token 不能为空");
    }

    const decoded = jwt.verify(token, process.env.SECRET);
    const { userId } = decoded;

    if (!userId) {
      throw new Error("receiverId 不能为空");
    }

    // 根据实际情况调整字段类型
    const updateCondition = {
      receiverId: parseInt(userId, 10), // 确保类型匹配
      status: "1",
    };

    await Message.update({ status: "2" }, { where: updateCondition });

    success(req, res, "一键已读成功。");
  } catch (error) {
    console.error("一键已读失败:", error);
    failure(req, res, error);
  }
});

/**
 * 查询消息详情
 * GET /admin/messages/:id
 */
router.get("/:id", async function (req, res) {
  try {
    const log = await getMessage(req);

    success(req, res, "查询消息成功详情。", { log });
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 修改消息
 * PUT /admin/messages/:id
 */
router.put("/:id", async function (req, res) {
  try {
    const log = await getMessage(req);
    const status = "2";
    await log.update({ status });
    success(req, res, "修改消息成功。");
  } catch (error) {
    failure(req, res, error);
  }
});

// /**
//  * 清空全部消息
//  * DELETE /admin/messages/clear
//  */
router.delete("/clear", async function (req, res) {
  try {
    await Message.destroy({ truncate: true });

    success(req, res, "清空消息成功。");
  } catch (error) {
    failure(req, res, error);
  }
});

// /**
//  * 删除消息
//  * DELETE /admin/messages/:id
//  */
// router.delete('/:id', async function (req, res) {
//   try {
//     const log = await getMessage(req);
//     await log.destroy();

//     success(req, res, '删除消息成功。');
//   } catch (error) {
//     failure(req, res, error);
//   }
// });
// 创建 新消息
router.post("/", async function (req, res) {
  try {
    const {
      title,
      content,
      senderId,
      receiverId,
      level,
      isObject,
      status,
      type,
      isWebSocket,
    } = req.body;
    if (
      !title ||
      !content ||
      !senderId ||
      !receiverId ||
      !level ||
      !isObject ||
      !status ||
      !type
    ) {
      throw new Error("缺少必要参数");
    }
    const log = await Message.create({
      title,
      content,
      senderId,
      receiverId,
      level,
      isObject,
      status,
      type,
      isWebSocket,
    });
    success(req, res, "创建消息成功。", { log });
  } catch (error) {
    failure(req, res, error);
  }
});

/**
 * 公共方法：查询当前消息
 */
async function getMessage(req) {
  const { id } = req.params;

  const log = await Message.findByPk(id);
  if (!log) {
    throw new NotFound(`ID: ${id}的消息未找到。`);
  }

  return log;
}

module.exports = router;
